<style rel="stylesheet/scss" lang="scss" scoped>
</style>

<template>
    <div>
        <div class="container">
            <el-card shadow="hover" style="padding:0">

                <!-- 操作按钮 -->
                <el-card class="operate_container" shadow="never">
                    <div class="wrapper">
                        <div><i class="el-icon-tickets" style="margin-right: 10px;"></i>数据列表</div>
                        <div>
                            <el-button type="primary" icon="el-icon-plus" size="medium" circle @click="addOrUpdateVisible"></el-button>
                            <el-button type="danger" icon="el-icon-delete" size="medium" circle @click="handleDelete"></el-button>
                            <el-button type="primary" icon="el-icon-refresh" size="medium" circle @click="handleResetSearch('searchForm')"></el-button>
                            <el-button type="primary" icon="el-icon-search" size="medium" circle @click="searchVisible = !searchVisible"></el-button>

                        </div>
                    </div>
                </el-card>

                <!-- 条件过滤 -->
                <el-card class="filter_container" shadow="never" v-show="searchVisible">
                    <div style="margin-top: 15px">
                        <el-form ref="searchForm" :inline="true" :model="searchForm" size="medium" label-width="120px">
                            <el-form-item label="Job名称" prop="jobName">
                                <el-input v-model="searchForm.jobName" clearable placeholder="Job名称"></el-input>
                            </el-form-item>
                            <el-form-item label=" ">
                                <el-button type="primary" @click="handleSearch()" size="medium">搜索</el-button>
                                <el-button @click="handleResetSearch('searchForm')" size="medium">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-card>

                <!-- 表格 -->
                <el-table
                    ref="table" size="small" empty-text="暂无数据"
                    element-loading-text="给我一点时间"
                    fit stripe border highlight-current-row
                    v-loading="dataListLoading"
                    :data="dataList"
                    :header-cell-style="{'padding-top': '10px', 'height': '50px', 'color': '#515A6E', 'background-color': '#f8f8f9'}"
                    @selection-change="handleSelection">
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column type="index" width="55" align="center"></el-table-column>

                    <el-table-column label="任务状态" width="80px" align="center">
                        <template slot-scope="scope">
                            <el-tag type="success" size="small" v-if="scope.row.jobStatus === 'RUNNING'">正常</el-tag>
                            <el-tag type="warning" size="small" v-if="scope.row.jobStatus === 'PAUSE'">暂停</el-tag>
                            <el-tag type="primary" size="small" v-if="scope.row.jobStatus === 'FINISHED'">完成</el-tag>
                            <el-tag type="danger" size="small" v-if="scope.row.jobStatus === 'FAILED'">失败</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="任务名称" prop="jobName" column-key="jobName" align="left" width="300"/>
                    <el-table-column label="执行表达式" prop="jobCron" width="200"/>
                    <el-table-column label="作业类" prop="jobClassPath" show-overflow-tooltip align="center" width="200"/>
                    <el-table-column label="作业参数" prop="jobParams"  show-overflow-tooltip align="center" width="200"/>
                    <el-table-column label="任务描述信息" prop="jobDesc" show-overflow-tooltip align="center" width="200"/>
                    
                    <el-table-column label="执行失败原因" prop="failureCause" show-overflow-tooltip width="200"/>
                    <el-table-column label="创建时间" prop="ctime" align="center" width="140"/>
                    <el-table-column label="最后更新时间" prop="utime" align="center" width="140"/>

                    <!--
                    <el-table-column label="状态" width="80px" align="center">
                        <template slot-scope="scope">
                            <el-tag type="success" size="small" v-if="scope.row.status === true">正常</el-tag>
                            <el-tag type="danger" size="small" v-else>禁用</el-tag>
                        </template>
                    </el-table-column>
                    -->

                    <el-table-column label="操作" width="350px" align="center" fixed="right">
                        <template slot-scope="scope">
                            <el-button type="primary" :disabled="scope.row.jobStatus === 'FINISHED' || scope.row.jobStatus === 'PAUSE'" size="small" @click="handlePauseJob(scope.row)">暂停</el-button>
                            <el-button type="primary" :disabled="scope.row.jobStatus === 'FINISHED' || scope.row.jobStatus === 'RUNNING'" size="small" @click="handleResumeJob(scope.row)">恢复</el-button>
                            <el-button type="primary" :disabled="scope.row.jobStatus === 'FINISHED' || scope.row.jobStatus === 'PAUSE'" size="small" @click="handleTriggerJob(scope.row)">触发</el-button>
                            <el-button type="primary" :disabled="scope.row.jobStatus === 'FINISHED'" size="small" @click="addOrUpdateVisible(scope.row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>

                </el-table>

                <!-- 分页工具栏 -->
                <div class="pagination">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="searchForm.page"
                            :page-sizes="[10, 20, 30, 50, 100, 200]"
                            :page-size="searchForm.limit"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="totalPage">
                    </el-pagination>
                </div>

                <!-- 窗口 -->
                <el-dialog
                    :title="!form.id ? '新增' : '修改'"
                    :visible.sync="visible" :close-on-click-modal="false" @close="handleDialogClose">
                    <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                        <el-form-item label="任务名称" prop="jobName">
                            <el-input v-model="form.jobName" placeholder="任务名称" style="width: 80%;"></el-input>
                        </el-form-item>
                        <el-form-item label="执行表达式" prop="jobCron">
                            <el-popover v-model="cronPopover">
                                <cron @change="changeCron" @close="cronPopover=false"></cron>
                                <el-input slot="reference" @click="cronPopover=true" v-model="form.jobCron" placeholder="请输入定时策略" style="width: 80%;"></el-input>
                            </el-popover>
                        </el-form-item>
                        <el-form-item label="作业类" prop="jobClassPath">
                            <el-select style="width: 80%;" v-model="form.jobClassPath" placeholder="作业类">
                                <template v-for="item in dicts.JOB_CLASS_PATH" >
                                    <el-option :disabled="!item.status" :label="item.label" :value="item.value" :key="item.id" no-data-text="无数据"/>
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="作业参数" prop="jobParams">
                            <el-row>
                                <el-col><el-button @click="addJobDataMap">添加参数</el-button></el-col>
                            </el-row>
                            <el-row style="margin-top: 10px" v-for="(item, index) in jobDataMapList" :key="index">
                                <el-col :span="5">
                                    <el-input v-model="item.key" placeholder="属性名" style="width: 80%;"></el-input>
                                </el-col>
                                <el-col :span="5">
                                    <el-input v-model="item.value" placeholder="属性值" style="width: 80%;"></el-input>
                                </el-col>
                                <el-col :span="5">
                                    <el-button type="danger" icon="el-icon-delete" circle size="small" @click="deleteJobDataMapList(index)"></el-button>
                                </el-col>
                            </el-row>
                        </el-form-item>
                        
                        <el-form-item label="描述信息" prop="jobDesc">
                            <el-input type="textarea" :rows="4" placeholder="请输入内容" style="width: 80%;" v-model="form.jobDesc"></el-input>
                        </el-form-item>

                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button @click="visible = false">取 消</el-button>
                        <el-button @click="handleSubmit('form')" type="primary" :loading="submitLoading">提 交</el-button>
                    </div>
                </el-dialog>
            </el-card>
        </div>
    </div>
</template>

<script>
import { save, deleted, updated, info, list, page, selectMyPage, pauseJob, resumeJob, triggerJob } from "@/api/admin/sysschedulerjob"
import { getDictByCode } from "@/api/admin/sysdict"
import { cron } from 'vue-cron'

export default {
    template: '<cron/>',
    components: { cron },
    data() {
        return {
            visible: false,
            searchVisible: false,
            submitLoading: false,

            dataList: [],
            totalPage: 0,
            dataListLoading: true,
            selectionRows: [],

            searchForm: {
                page: 1,
                limit: 10,
                sortColumns: null,
                sortType: null
            },
            form: {
                id: null,
                jobName: null,
                jobGroup: null,
                jobCron: null,
                jobTriggerDate: null,
                jobClassPath: null,
                jobParams: null,
                jobDesc: null,
                jobStatus: null,
                failureCause: null,
                jobDataMapList: null,
                remarks: null,
                ctime: null,
                utime: null
            },
            rules: {
                jobName: [
                    { required: true, message: 'Job名称不能为空', trigger: 'blur' }
                ],
                jobCron: [
                    { required: true, message: '执行的cron不能为空', trigger: 'blur' }
                ],
                jobTriggerDate: [
                    { required: true, message: '任务触发时间不能为空', trigger: 'blur' }
                ],
                jobClassPath: [
                    { required: true, message: 'Job作业类不能为空', trigger: 'blur' }
                ]
            },
            cronPopover: false,
            dicts: {},

            jobDataMapList: []
        }
    },
    mounted() {
    	this.$nextTick(function () {
            this.getDataList()
            
            this.initDict()
    	})
    },
    methods: {
        addJobDataMap() {
            this.jobDataMapList.push({key: null, value: null})
        },
        deleteJobDataMapList(index) {
            this.jobDataMapList.splice(index, 1)
        },
        initDict() { //获取字典
            const dictCodes = ['JOB_CLASS_PATH']
            getDictByCode({codes: dictCodes}).then(res => {
                if(res.status) {
                    this.dicts = res.data
                    for(let code of dictCodes) { //设置初始默认值
                        this.dicts[code].filter((item) => {
                            if('JOB_CLASS_PATH' === code) {
                                if(item.selected)
                                    this.form.jobClassPath = item.value
                            }
                        })
                    }
                }
            })
        },
        changeCron(val){ // Cron
            this.form.jobCron=val
        },

        handleSelection(selection) { // 多选
            this.selectionRows = selection
        },
        handleSizeChange(val) { // 每页数量
            this.searchForm.limit = val
            this.getDataList()
        },
        handleCurrentChange(val) { // 页码
            this.searchForm.page = val
            this.getDataList()
        },
        handleResetSearch(name) { // 重置搜索表单
            this.handleReset(name)
            this.getDataList()
        },
        handleReset(name) { // 重置表单
            const refs = this.$refs
            refs[name].resetFields()
        },
        handleSearch() { // 单条件搜索
            this.getDataList()
        },
        handleDialogClose() { //表单窗口关闭
            this.form.jobDataMapList = []
            this.jobDataMapList = []
            this.handleReset('form')
        },

		/**
         * 打开表单窗口
         */
		addOrUpdateVisible(row) {
            this.visible = true
            if (row.id) {
                this.getInfo(row.id).then(res => {
                    this.form = Object.assign({}, res.data)

                    if(this.form.jobParams) {
                        let params = JSON.parse(this.form.jobParams)
                        this.form.jobDataMapList = params
                        this.jobDataMapList = params
                    }
                })
            } else {
                this.form.id = null
            }
        },

		/**
         * 提交表单
         */
        handleSubmit(name) {
        	const refs = this.$refs
            refs[name].validate((valid) => {
                if (valid) {
                    this.submitLoading = true

                    if(this.jobDataMapList.length > 0) {
                        this.form.jobDataMapList = this.jobDataMapList
                    }

                    if (!this.form.id) {
                        save(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.visible = false
                                this.handleReset('form')
                                this.getDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else if (this.form.id) {
                        updated(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.visible = false
                                this.handleReset('form')
                                this.getDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else {
                        console.log('未知操作');
                    }
                }
            })
        },
		
		/**
         * 删除
         */
        handleDelete(row) { 
            let ids = []
            if (row.id != undefined) {
                ids.push(row.id)
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {    
                this.$confirm('确定要删除？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
                    deleted({ idList: ids }).then(res => {
                        if (this.ResultMessage(res)) {
                            this.getDataList()
                        } 
                    }).catch(error => {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    })
                }).catch(() => {})
            }
        },

		/**
         * 详细信息
         */
        getInfo(id) {
            if (id !== undefined) {
                return info(id).then(res => {
                    if (this.ResultMessage(res, false)) {
                        return res
                    } else {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    }
                }).catch(error => {
                    this.$notify({ title: '错误', message: error, type: 'error' });
                })
            }
        },
		
        /**
         * 数据列表
         */
        getDataList() {
            page(this.searchForm).then(res => {
                if (this.ResultMessage(res, false)) {
                    this.dataList = res.data.records
                    this.totalPage = res.data.total
                    this.dataListLoading = false
                } else {
                    this.dataListLoading = false
                }
            }).catch(error => {
                this.dataListLoading = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        },

        handlePauseJob(row) { // 暂停任务
            pauseJob({'id': row.id, 'jobName': row.jobName, 'jobGroup': row.jobGroup}).then(res => {
                if (this.ResultMessage(res)) {
                    this.getDataList()
                }
            }).catch(error => {
                this.submitLoading = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        },

        handleResumeJob(row) { // 恢复任务
            resumeJob({'id': row.id, 'jobName': row.jobName, 'jobGroup': row.jobGroup}).then(res => {
                if (this.ResultMessage(res)) {
                    this.getDataList()
                }
            }).catch(error => {
                this.submitLoading = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        },

        handleTriggerJob(row) { // 触发任务
            this.loading = true
            triggerJob({'id': row.id, 'jobName': row.jobName, 'jobGroup': row.jobGroup}).then(res => {
                if (this.ResultMessage(res)) {
                    setTimeout(()=>{
                        this.getDataList()
                    }, 1000)
                }
            }).catch(error => {
                this.submitLoading = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        }
    }
}
</script>